package com.longcai.controller.fee;


import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.auth.ClyjShopsArea;
import com.longcai.entity.fee.ClyjFeeArea;
import com.longcai.entity.fee.ClyjFeeFormwork;
import com.longcai.entity.fee.ClyjFeeFormworkDetail;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.fee.ClyjFeeAreaService;
import com.longcai.service.fee.ClyjFeeFormworkDetailService;
import com.longcai.service.fee.ClyjFeeFormworkService;
import com.longcai.util.UUIDUtil;

import io.swagger.annotations.ApiOperation;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 运费模板表 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-05-09
 */
@Controller
@RequestMapping("/clyjFeeFormwork")
public class ClyjFeeFormworkController {
	@Autowired
	private ClyjFeeFormworkService feeService;
	@Autowired
	private ClyjFeeAreaService areaService;
	@Autowired
	private ClyjFeeFormworkDetailService detailService;
	
	/**
	 * 获取所有模板列表
	 * 
	 */
	@RequestMapping("/getFee")
	@ResponseBody
	public PageTableResponse saveGoodSolr(ClyjFeeFormwork fee, PageHelper pageHelper) {
    	Page<ClyjFeeFormwork> page = new Page<ClyjFeeFormwork>(pageHelper.getStart(), pageHelper.getLength());
    	QueryWrapper<ClyjFeeFormwork> w = new QueryWrapper<ClyjFeeFormwork>();
    	if(fee.getFormworkName()!=null && fee.getFormworkName()!="")
    		w.like("formwork_name", fee.getFormworkName());
        IPage<ClyjFeeFormwork> sysRoleIPage = this.feeService.selectPage(page, w);
        List<ClyjFeeFormwork> feeList = sysRoleIPage.getRecords();
        for (ClyjFeeFormwork clyjFeeFormwork : feeList) {
        	String formworkId = clyjFeeFormwork.getFormworkId();
        	clyjFeeFormwork = getArea(clyjFeeFormwork,formworkId);
		}
        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
         return pageTableResponse;
    }
	
	@GetMapping("{id}")
    @ApiOperation(value = "根据id获取模板")
    @ResponseBody
    public ClyjFeeFormwork get(@PathVariable String id) {
        ClyjFeeFormwork fee = feeService.selectById(id);
        fee=getArea(fee, id);
        return fee;
    }

    
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除模板")
    @ResponseBody
    public void delete(@PathVariable String id) {
        this.feeService.deleteById(id);
    }
    
    public ClyjFeeFormwork getArea(ClyjFeeFormwork clyjFeeFormwork,String formworkId){
    	//根据模板id查询明细中的配送范围
    	QueryWrapper<ClyjFeeFormworkDetail> detailQuery = new QueryWrapper<ClyjFeeFormworkDetail>();
    	detailQuery.eq("formwork_id", formworkId);
    	List<ClyjFeeFormworkDetail> selectList = detailService.selectList(detailQuery);
    	String area = "";
    	if(selectList==null || selectList.size()==0)
    		return clyjFeeFormwork;
    	clyjFeeFormwork.setDetailList(selectList);
    	for (ClyjFeeFormworkDetail clyjFeeFormworkDetail : selectList) {
    		String detailId = clyjFeeFormworkDetail.getDetailId();
    		QueryWrapper<ClyjFeeArea> areaQuery = new QueryWrapper<ClyjFeeArea>();
    		areaQuery.eq("detail_id", detailId);
    		areaQuery.orderByAsc("area_id");
        	List<ClyjFeeArea> areaList = areaService.selectList(areaQuery);
        	if(areaList==null || areaList.size()==0)
        		continue;
        	String detailArea = "";
        	String AreaId = "";
        	for (ClyjFeeArea clyjFeeArea : areaList) {
        		area+=";"+clyjFeeArea.getAreaName();
        		detailArea+=";"+clyjFeeArea.getAreaName();
        		AreaId+=";"+clyjFeeArea.getAreaId();
			}
        	if(detailArea.equals("")|| detailArea.length()==0)
        		clyjFeeFormworkDetail.setDetailArea(detailArea);
        	else{
	        	detailArea = detailArea.substring(1);
	        	AreaId = AreaId.substring(1);
	        	clyjFeeFormworkDetail.setDetailArea(detailArea);
	        	clyjFeeFormworkDetail.setAreaId(AreaId);
        	}
		}
    	if(area.equals("")|| area.length()==0)
    		return clyjFeeFormwork;
    	area=area.substring(1);
    	clyjFeeFormwork.setArea(area);
    	return clyjFeeFormwork;
    }
    
    /**
	 * 获取所有地区
	 * 
	 */
    @GetMapping("/getAllArea")
    @ApiOperation(value = "所有地区")
    @ResponseBody
    public JSONArray goodsClassAll(String type) {
        List<ClyjShopsArea> selectList = areaService.selectAllArea();
        JSONArray array = new JSONArray();
        setPermissionsTree(0, selectList, array);

        return array;
    }
    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(Integer pId, List<ClyjShopsArea> permissionsAll, JSONArray array) {
        permissionsAll.forEach(a -> {
            if ((pId==0 && a.getParentId() == null) || (a.getParentId() != null && a.getParentId()==pId)) {
                String string = JSONObject.toJSONString(a);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getParentId() != null && p.getParentId()==a.getId()).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(a.getId(), permissionsAll, child);
                }
            }
        });
    }
    /**
	 * 获取所有模板列表
	 * 
	 */
	@RequestMapping("/saveFee")
	@ResponseBody
	public ApiResult saveFee(ClyjFeeFormwork fee,ClyjFeeFormworkDetail detail) {
		//定义主键
		String formworkId = UUIDUtil.uuid();
		fee.setUpdateTime(LocalDateTime.now());
		try{
			//保存模板
			if(fee.getFormworkId()==null || fee.getFormworkId().equals("")){
				fee.setFormworkId(formworkId);
				feeService.insert(fee);
			}else{
				feeService.updateById(fee);
				//删除detail和区域表
				QueryWrapper<ClyjFeeFormworkDetail> detailDelquery = new QueryWrapper<ClyjFeeFormworkDetail>();
				detailDelquery.eq("formwork_id", fee.getFormworkId());
				detailService.delete(detailDelquery);
				//删除区域
				QueryWrapper<ClyjFeeArea> areaDelquery = new QueryWrapper<ClyjFeeArea>();
				areaDelquery.eq("formwork_id", fee.getFormworkId());
				areaService.delete(areaDelquery);
			}
			//新增detail
			String detailAreas = detail.getDetailArea();
			if(detailAreas==null || detailAreas.equals(""))
				return ApiResult.success();
			String[] detailArea = detailAreas.split(",");
			String areaIds = detail.getAreaId()==null?"":detail.getAreaId();
			String[] areaId = areaIds.split(",");
			String firstNums = detail.getFirstNum()==null?"":detail.getFirstNum();
			String[] firstNum = firstNums.split(",");
			String firstPrices = detail.getFirstPrice()==null?"":detail.getFirstPrice();
			String[] firstPrice = firstPrices.split(",");
			String nextNums = detail.getNextNum()==null?"":detail.getNextNum();
			String[] nextNum = nextNums.split(",");
			String nextPrices = detail.getNextPrice()==null?"":detail.getNextPrice();
			String[] nextPrice = nextPrices.split(",");
			for (int i=0;i<detailArea.length;i++) {
				ClyjFeeFormworkDetail insertDetail = new ClyjFeeFormworkDetail();
				insertDetail.setDetailId(UUIDUtil.uuid());
				insertDetail.setFormworkId(fee.getFormworkId());
				insertDetail.setFirstNum(firstNum[i]==null?"":firstNum[i]);
				insertDetail.setFirstPrice(firstPrice[i]==null?"":firstPrice[i]);
				insertDetail.setNextNum(nextNum[i]==null?"":nextNum[i]);
				insertDetail.setNextPrice(nextPrice[i]==null?"":nextPrice[i]);
				detailService.insert(insertDetail);
				//新增区域
				String area = detailArea[i];
				String[] areas = area.split(";");
				String aid = areaId[i];
				String[] aids = aid.split(";");
				for (int j=0;j<areas.length;j++ ) {
					ClyjFeeArea ar = new ClyjFeeArea();
					ar.setAreaId(aids[j]);
					ar.setAreaName(areas[j]);
					ar.setFormworkId(fee.getFormworkId());
					ar.setDetailId(insertDetail.getDetailId());
					ar.setId(UUIDUtil.uuid());
					areaService.insert(ar);
				}
			}
			return ApiResult.success();
		}catch(Exception e){
			e.printStackTrace();
			return ApiResult.fail("保存失败"+e.getMessage());
		}
       
    }
}

